package com.wangdao.wechatmall.service.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wangdao.wechatmall.bean.bo.admin.AdminCreateBO;
import com.wangdao.wechatmall.bean.bo.admin.AdminParamBO;
import com.wangdao.wechatmall.bean.bo.admin.AdminUpdateBO;
import com.wangdao.wechatmall.bean.pojo.Admin;
import com.wangdao.wechatmall.bean.pojo.AdminExample;
import com.wangdao.wechatmall.bean.pojo.User;
import com.wangdao.wechatmall.bean.vo.admin.AdminCreateVO;
import com.wangdao.wechatmall.bean.vo.admin.AdminDataVO;
import com.wangdao.wechatmall.bean.vo.admin.AdminVO;
import com.wangdao.wechatmall.bean.vo.wx.WXLoginVO;
import com.wangdao.wechatmall.exception.AdminDuplicatedException;
import com.wangdao.wechatmall.exception.AdminEmptyException;
import com.wangdao.wechatmall.exception.AdminPassWordException;
import com.wangdao.wechatmall.exception.AdminUserNameException;
import com.wangdao.wechatmall.mapper.AdminMapper;
import com.wangdao.wechatmall.mapper.UserMapper;
import com.wangdao.wechatmall.util.DateTransformUtil;
import com.wangdao.wechatmall.util.StringTransformUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author ZhangXiao on 2021/7/8
 * @ClassName: AdminServiceImpl
 * @Description 管理员service
 * @Author Xinhao Yi
 * @Date 2021/7/8  21:03
 */

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    AdminMapper adminMapper;


    /**
     * 查询管理员
     * Xinhao Yi
     *
     * @param param
     * @return
     */

    @Override
    public AdminDataVO queryAdmin(AdminParamBO param) {
        //分页
        PageHelper.startPage(param.getPage(), param.getLimit());
        //根据username是否为null构造查询条件
        //根据sort和order去写排序
        //里面包含List<Criterion> 条件列表
        AdminExample adminExample = new AdminExample();
        AdminExample.Criteria criteria = adminExample.createCriteria();
        if (param.getUsername() != null) {
            criteria.andUsernameLike("%" + param.getUsername() + "%");
        }
        //不要拿已经被删除了的
        criteria.andDeletedEqualTo(false);
        //一定要注意这里两者之间要有空格
        adminExample.setOrderByClause(param.getSort() + " " + param.getOrder());
        //查找，拿到管理员序列
        List<Admin> admins = adminMapper.selectByExample(adminExample);

        //创建用于保存结果的 adminVoList
        List<AdminVO> adminVoList = new ArrayList<>();
        for (Admin admin : admins) {
            AdminVO adminVo = new AdminVO();
            adminVo.setId(admin.getId());
            adminVo.setUsername(admin.getUsername());
            adminVo.setAvatar(admin.getAvatar());
            //拿到getRoleIds，把它转换为list<Integer>
            //todo
//            String str = admin.getRoleIds();
            Integer[] roleIdsTemp = admin.getRoleIds();
            List<Integer> roleIds = StringTransformUtils.integerArray2List(roleIdsTemp);
            //创建用于接受结果的List<Integer> roleIds
//            List<Integer> roleIds = StringTransformUtils.string2IntegerList(str);
            //set进adminVo中
            //
            adminVo.setRoleIds(roleIds);
            //add进adminVoList中
            adminVoList.add(adminVo);
        }
        //再去拿去total
        //total可以使用countByExample，也可以使用PageHelper来获得
        //方法一：使用countByExample
        //int total = adminExample.countByExample(adminExample);

        //方法二：使用PageInfo
        //在执行查询之后可以获得分页信息,将查询结果放入PageInfo的构造方法里
        PageInfo<AdminVO> pageInfo = new PageInfo<>(adminVoList);
        int total = (int) pageInfo.getTotal();

        return AdminDataVO.ok(total, adminVoList);
    }


    /**
     * 创建管理员
     * Xinhao Yi
     *
     * @param param
     * @return
     */
    @Override
    public AdminCreateVO createAdmin(AdminCreateBO param) throws AdminUserNameException, AdminPassWordException, AdminEmptyException, AdminDuplicatedException {
        //先进行数据校验
        //首先要判断admin的数据是否为空
        if (StringUtils.isEmpty(param.getUsername()) || StringUtils.isEmpty(param.getPassword())) {
            throw new AdminEmptyException();
        }
        //校验输入的用户名和密码的格式对不对
        /*
          如果用户名异常（比如长度大于10）,返回到用户名异常页面
          如果密码异常（比如过短，比如不包含字母）,返回到密码异常页面
         */
        if (param.getUsername().length() > 10) {
            throw new AdminUserNameException();
        }

        //用正则表达式来判断password中是否含有字母，以及长度是否合乎规范
        String pattern = "[a-z|A-Z]";
        Pattern r = Pattern.compile(pattern);
        Matcher matcher = r.matcher(param.getPassword());

        if (param.getPassword().length() < 3 || param.getPassword().length() > 15 || !matcher.find()) {
            throw new AdminPassWordException();
        }

        //查询管理员的用户名是否重复
        AdminExample adminExample = new AdminExample();
        AdminExample.Criteria criteria = adminExample.createCriteria();

        if (param.getUsername() != null) {
            criteria.andUsernameEqualTo(param.getUsername());
        }
        List<Admin> admins = adminMapper.selectByExample(adminExample);
        if (admins.size() > 0) {
            throw new AdminDuplicatedException();
        }

        //创建admin
        Admin admin = new Admin();

        //当前时间戳
        Date date = new Date(System.currentTimeMillis());
        //调用工具类格式化时间
        Date dateFormatted = DateTransformUtil.dateFormat(date);
        admin.setAddTime(dateFormatted);
        admin.setUpdateTime(dateFormatted);
        //其他成员赋值
        admin.setUsername(param.getUsername());
        admin.setPassword(param.getPassword());
        //要把List<Integer> getRoleIds() 转化为Integer[]类型
        Integer[] roleIds = StringTransformUtils.list2IntegerArray(param.getRoleIds());
        admin.setRoleIds(roleIds);
        admin.setDeleted(false);
        admin.setAvatar(param.getAvatar());
        //把admin插入到数据库中
        int affectedLine = adminMapper.insertSelective(admin);
        //再来构造AdminCreateVO
        AdminCreateVO adminCreateVO = new AdminCreateVO();
        //查找刚才插入的admin的生成的id，也就是最大的id
        Integer id = adminMapper.selectMaxId();
        //封装
        AdminCreateVO returnAdminCreateVO = AdminCreateVO.ok(id, param.getUsername(), param.getPassword(), param.getAvatar(), dateFormatted, dateFormatted, param.getRoleIds());
        return returnAdminCreateVO;
    }

    @Override
    public AdminCreateVO update(AdminUpdateBO param) throws AdminEmptyException, AdminUserNameException, AdminPassWordException, AdminDuplicatedException {
        //先进行数据校验
        //首先要判断admin的数据是否为空
        if (StringUtils.isEmpty(param.getUsername()) || StringUtils.isEmpty(param.getPassword())) {
            throw new AdminEmptyException();
        }
        //校验输入的用户名和密码的格式对不对
        /*
          如果用户名异常（比如长度大于10）,返回到用户名异常页面
          如果密码异常（比如过短，比如不包含字母）,返回到密码异常页面
         */
        if (param.getUsername().length() > 10) {
            throw new AdminUserNameException();
        }

        //用正则表达式来判断password中是否含有字母，以及长度是否合乎规范
        String pattern = "[a-z|A-Z]";
        Pattern r = Pattern.compile(pattern);
        Matcher matcher = r.matcher(param.getPassword());

        if (param.getPassword().length() < 3 || param.getPassword().length() > 15 || !matcher.find()) {
            throw new AdminPassWordException();
        }

        //用户名重复，即不修改用户名，也是可以的

        //到这里检验合格
        //创建admin
        Admin admin = new Admin();
        //当前时间戳
        Date date = new Date(System.currentTimeMillis());
        //调用工具类格式化时间
        Date dateFormatted = DateTransformUtil.dateFormat(date);
        admin.setUpdateTime(dateFormatted);
        //其他成员赋值
        admin.setId(param.getId());
        admin.setUsername(param.getUsername());
        admin.setPassword(param.getPassword());
        //要把List<Integer> getRoleIds() 转化为String类型
        Integer[] roleIds = StringTransformUtils.list2IntegerArray(param.getRoleIds());
        admin.setRoleIds(roleIds);
        admin.setDeleted(false);
        admin.setAvatar(param.getAvatar());

        //有选择性地更新数据库
        adminMapper.updateByPrimaryKeySelective(admin);

        //封装
        AdminCreateVO returnAdminCreateVO = AdminCreateVO.ok(param.getId(), param.getUsername(), param.getPassword(), param.getAvatar(), null, dateFormatted, param.getRoleIds());

        return returnAdminCreateVO;

    }

    @Override
    public void delete(AdminUpdateBO param) {
        int id = param.getId();
        Admin admin = new Admin();
        admin.setId(id);
        admin.setDeleted(true);
        adminMapper.updateByPrimaryKeySelective(admin);
    }

    @Override
    public Admin queryAdminByName(String username) {
        Admin admin = adminMapper.queryAdminByName(username);
        return admin;
    }

}


